package com.dingding.service.activity.core.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.common.core.base.dao.impl.BaseDaoImpl;
import com.dingding.common.core.beans.Activity;
import com.dingding.common.core.beans.ActivityInfoBanner;
import com.dingding.common.core.beans.City;
import com.dingding.common.core.config.Constants;
import com.dingding.common.core.util.ToolUtil;
import com.dingding.facde.activity.dto.indexmodule.GetIndexModulesDto;
import com.dingding.facde.activity.dto.shareplan.SharePlanDto;
import com.dingding.service.activity.core.dao.IActivityDao;
import com.dingding.service.activity.core.dao.IActivityInfoBannerDao;
import com.dingding.service.activity.core.sql.ActivitySQL;
import com.dingding.service.activity.core.sql.IndexModuleSQL;

/**
 * @ClassName: ActivityDaoImpl
 * @Description: 活动模块DAO实现类
 * @author yuHaiQing
 * @date 2016年3月24日 上午11:38:56
 */
@Component("activityDao")
public class ActivityDaoImpl extends BaseDaoImpl<Activity> implements IActivityDao {

	@Resource(name = "activityInfoBannerDao")
	private IActivityInfoBannerDao activityInfoBannerDao;

	/**
	 * @Title: getActivityList
	 * @Description: 获取全部有效的活动列表
	 * @author yuHaiQing
	 * @return List<Activity> 活动列表
	 */
	@Override
	@Transactional(readOnly = true)
	public List<Activity> getActivityList() {
		// 设置获取全部活动的条件（有效的活动）
		Criterion criterion = Restrictions.eq("snSatatus", 1);

		// 声明用户存储全部的活动累吧
		List<Activity> activities = null;
		try {
			activities = super.queryCriteriaListByOrder(criterion, Order.desc("createTime"));
		} catch (Exception e) {
			log.error("获取全部有效的活动列表时出现异常，类：" + this.getClass() + " getActivityList()", e);
		}
		
		//如果活动不是空的
		if(activities != null && activities.size() > 0){
			for(Activity ac : activities){
				ac.setPropagandaImage(ToolUtil.imageAddress(ac.getPropagandaImage()));
			}
		}

		return activities;
	}

	/**
	 * @Title: getActivityInfo
	 * @Description: 根据活动Id获取活动详情
	 * @param snId
	 *            活动Id
	 * @author yuHaiQing
	 * @return Activity 活动详情
	 */
	@Override
	@Transactional(readOnly = true)
	public Activity getActivityInfo(String snId) {

		// 声明存储活动详情的对象
		Activity activity = null;

		try {
			// 根据活动Id获取活动详情
			activity = super.getById(snId);
		} catch (Exception e) {
			log.error("根据活动Id获取活动详情时出现异常  类：" + this.getClass() + " getActivityInfo()", e);
		}

		// 获取活动详情banner图片
		ActivityInfoBanner banner = activityInfoBannerDao.getActivityDetailBanner(snId);

		// 设置详情的banner图片
		if (activity != null && banner != null) {
			activity.setPropagandaImage(banner.getBannerImageName());
		}

		return activity;
	}

	/**
	 * @Title: resetInvalidActivity
	 * @Description: 重置无效活动
	 * @author YHQ
	 * @return boolean true:重置成功 false:失败
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean resetInvalidActivity() {

		// 返回受影响行数
		int row = -1;

		try {
			row = super.updateSqlRow(ActivitySQL.RESET_INVALID_ACTIVITY);
		} catch (Exception e) {
			log.error("重置无效活动时出现异常  类：" + this.getClass() + " resetInvalidActivity()", e);
		}

		// 判断是否重置成功，如果row为负数，则重置活动失败
		if (row < 0) {
			return false;
		}

		return true;
	}

	/**
	 * @Description: 获取用户活动列表
	 * @param userId
	 *            用户登录id
	 * @param pageIndex
	 *            当前页
	 * @author fengshuonan
	 * @return List<Activity> 活动列表
	 * @since 2.3.2
	 */
	@Override
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Activity> getActivityList(String userId, Integer pageIndex) {

		// 设置获取全部活动的条件（有效的活动）
		Criterion criterion = Restrictions.eq("snSatatus", 1);

		// 声明用户存储全部的活动累吧
		List<Activity> activities = null;
		
		try {
			activities = super.getCriteria()
					.addOrder(Order.desc("createTime"))
					.add(criterion).setFirstResult(Constants.MAX_ACTIVITY_LIST_SIZE * (pageIndex-1))
					.setMaxResults(Constants.MAX_ACTIVITY_LIST_SIZE).list();
		} catch (Exception e) {
			log.error("获取全部有效的活动列表时出现异常，类：" + this.getClass() + " getActivityList(userId,pageIndex)", e);
			return null;
		}
		
		List<Activity> newList = new ArrayList<Activity>();
		
		//拼接url地址,并放入新的容器
		for(Activity ac : activities){
			Activity temp = new Activity();
			BeanUtils.copyProperties(ac, temp);
			temp.setVisitUrl(ac.getVisitUrl() + "&bizId=" + userId);
			newList.add(temp);
		}

		return newList;
	}

	
	/**
	 * @Description: 获取主页模块列表
	 * @param cityNo 城市编号
	 * @author fengshuonan
	 * @return List<GetIndexModulesDto>
	 * @since 2.4
	 */
	@Override
	@SuppressWarnings("unchecked")
	public List<GetIndexModulesDto> getIndexModuleList(String cityNo) {
		
		//先判断首页城市列表有没有这个城市，如果没有，就默认为其他
		List<City> cities = (List<City>) super.listSqlToCustomBean("select * from city where isServiceCity = 2 and cityNo = ?", City.class, cityNo);
		if(cities == null || cities.size() <= 0){
			cityNo = "9999";//9999为数据库其他城市
		}
		
		List<GetIndexModulesDto> list = null;
		
		List<String> fields = new ArrayList<String>();
		fields.add("useType");
		fields.add("moduleName");
		fields.add("webViewUrl");
		
		try {
			list = (List<GetIndexModulesDto>) super.listSqlToCustomBean(IndexModuleSQL.GET_INDEX_MODULE, 0, 0, GetIndexModulesDto.class, fields, cityNo);
		} catch (Exception e) {
			log.error("查询主页模块列表的时候出错！" + this.getClass() + ":getIndexModuleList()",e);
		}
		if(list == null || list.size() <= 0){
			return null;
		}else{
			return list;
		}
	}

	/**
	 * @Description:获取共享计划列表
	 * @param cityNo 城市编号
	 * @author fengshuonan
	 * @return List<SharePlanDto> 共享计划列表
	 * @since 2.4
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<SharePlanDto> getSharePlanList(String cityNo) {
		
		List<SharePlanDto> list = null;
		
		List<String> fields = new ArrayList<String>();
		fields.add("activityId");
		fields.add("createTime");
		fields.add("banner");
		fields.add("title");
		fields.add("content");
		
		try {
			list = (List<SharePlanDto>) super.listSqlToCustomBean(ActivitySQL.GET_SHARE_PLANE_LIST, 0, 0, SharePlanDto.class, fields, cityNo);
		} catch (Exception e) {
			log.error("获取共享计划列表的时候出错！" + this.getClass() + ":getSharePlanList()",e);
			return null;
		}
		
		if(list == null || list.size() <= 0){
			return null;
		}else{
			return list;
		}
	}
}
